package com.xsh.opensltest;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class MyAudioTrackIns extends Activity
{
    // AudioTrack是Android系统提供的用于播放PCM格式音频数据的工具类，它直接和音频硬件驱动交互，负责将从上层接收到的音频数据（PCM格式）从扬声器或者耳机输出；
    private AudioTrack audioTrack;
    private volatile double currentFrequency = 440.0;
    private volatile boolean isPlaying = false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audiotrackins);
        initAudioTack();
        initPianoView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(audioTrack!=null)
        {
            audioTrack.stop();
            audioTrack.release();
        }

    }
    private void initPianoView()
    {

    }
    private void initAudioTack()
    {
        int sampleRate = 44100;
        int bufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT);
        audioTrack = new AudioTrack(
                AudioManager.STREAM_MUSIC,
                sampleRate,
                AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                bufferSize,
                AudioTrack.MODE_STREAM
        );
    }
    public void testSine(View v)
    {
        if (isPlaying) {
            // 停止播放
            isPlaying = false;
            audioTrack.stop();
        } else {
            // 开始播放
            isPlaying = true;
            audioTrack.play();

            // 启动后台线程生成并写入音频数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int sampleRate = 44100;
                    int bufferSize = 1024; // 每次写入的采样点数
                    short[] buffer = new short[bufferSize];
                    double phase = 0.0;

                    // 计算相位增量（频率相关的步长）
                    double phaseIncrement = 2 * Math.PI * currentFrequency / sampleRate;

                    while (isPlaying) {
                        // 生成正弦波数据
                        for (int i = 0; i < bufferSize; i++) {
                            buffer[i] = (short) (Math.sin(phase) * 32767); // 16位PCM
                            phase += phaseIncrement;
                            // 相位回绕避免溢出
                            if (phase > 2 * Math.PI) phase -= 2 * Math.PI;
                        }

                        // 将 short[] 转换为 byte[]
                        byte[] byteBuffer = new byte[bufferSize * 2];
                        ByteBuffer.wrap(byteBuffer)
                                .order(ByteOrder.LITTLE_ENDIAN)
                                .asShortBuffer()
                                .put(buffer);

                        // 写入音频数据
                        audioTrack.write(byteBuffer, 0, byteBuffer.length);
                    }
                }
            }).start();
        }
    }
}
